// import { draw } from './utils'
import { DrawOption } from './typing'
import { ref, Ref } from 'vue'
/**
 *
 * @param {*} options
 * @returns
 */

export default function(useOption: DrawOption, initWidth: Ref<number>): void {
  const {
    el,
    drawType = ['left', 'right', 'top', 'bottom'],
    onDrawStart,
    onDrawEnd
  } = useOption

  if (!el) throw new Error(`参数el不能为${el}`)
  if (!(el instanceof HTMLElement)) throw new Error(`参数el必须为HTMLElement对象`)
  if (!drawType.length) throw new Error('drawType可不传，或至少包含“left”,“right”,“top”,“bottom”其中之一')


  let off = false
  function drawMousemove(e:any): void {
    const { clientWidth } = el
    let { inRight } = mousemoveToBoder(el, e)

    if(drawType === undefined) return
    inRight = inRight && drawType.includes('right')

    if (inRight) {
      el.style.cursor = 'w-resize' // 纵向拉伸鼠标样式
    } else {
        el.style.cursor = 'default'
        el.onmousedown = null
      return
    }

    // 获取dom当前为位置
    el.onmousedown = function(e){
      el.style.transition = 'none' // 清楚过渡效果
      if(!off){
        // 执行一次开始拉伸回调
        if(onDrawStart) onDrawStart()
        off = true
      }
      const clientX = e.clientX
      const elW = clientWidth
      el.style.userSelect = 'none'
      // 当鼠标位置不在可触发拉伸范围
      if (!inRight) return

      document.onmousemove = (e: any) => {
        // 移动时禁用默认事件
        e.preventDefault()
        const xWidht = e.clientX - clientX
        // 右侧鼠标拖拽位置
        if (inRight) {
          initWidth.value = elW + xWidht
          el.classList.remove('cr_body_menus-hover')
          return
        }
      }
      // 拉伸结束
      document.onmouseup = function(e) {
        document.onmousemove = null
        document.onmouseup = null
        el.style.transition = 'all .2s' // 恢复过渡效果
        el.classList.add('cr_body_menus-hover')
        // 执行一次拉伸结束回调
        if(onDrawEnd) onDrawEnd()
        off = false
      }
    }
  }
  el.addEventListener('mousemove', drawMousemove)
}


function mousemoveToBoder(draBodyDom: HTMLElement, e: any){
  const { offsetLeft, offsetTop, clientWidth, clientHeight, scrollTop } = draBodyDom

  const domBound = draBodyDom.getBoundingClientRect()
  const rBor = domBound.left + clientWidth // dom右侧边框在视口的位置
  const bBor = domBound.top + clientHeight // dom底部边框在视口位置

  // 鼠标在左侧边框上
  const inLeft = offsetLeft + 10 > e.clientX && e.clientX > offsetLeft + 1 // && drawType.includes('left')
  // 鼠标在右侧边框上
  const inRight = e.clientX > rBor - 10 && e.clientX < rBor + 1 // && drawType.includes('right')
  // 鼠标在dom底部边框上
  const inBottom = scrollTop + e.clientY > bBor - 10 && scrollTop + e.clientY < bBor - 1 // && drawType.includes('bottom')
  // 鼠标在dom顶部边框上
  const inTop = e.clientY < offsetTop + 10 // && drawType.includes('top')
  return {
    inLeft,
    inRight,
    inBottom,
    inTop
  }
}

